<script setup>
import {onBeforeMount, ref} from "vue";
import router from "@/router/index.js";
import {cancelCollect, collect, getArticleById, like} from "@/api/request.js";
import {useRoute} from "vue-router";
import {useUserStore} from "@/store/user.js";
import {showToast} from "vant";
import Remark from "@/components/remark.vue";
import DisplayHTML from "@/components/displayHTML.vue";
import {goBackToThePreviousPage} from "@/util/common.js";
import ArticleItem from "@/components/articleItem.vue";

const store = useUserStore()
const articleId = Number(useRoute().params.id)

const showRemarkBox = ref(false) // 弹出评论弹出框
const relatedArticle = ref(null)

const articleDetail = ref({
  article: {
    id: 0,
    title: '',
    content: '',
    updateTime: '',
    userId: 0,
    articleId: 0
  },
  user: {
    id: 0,
    username: '',
    avatar: '',
  },
  knowledgeBases: [{
    id: 0,
    name: '',
    icon: '',
    backgroundColor: ''
  }],
  collect: false,
  like: false
})

onBeforeMount(async () => {
  // 根据文章id获取文章
  await getArticleById({
    userId: store.userId,
    articleId: articleId
  }).then(res => {
    if (res.data !== null) {
      console.log(res.data)
      articleDetail.value = res.data
    }
  })

  console.log(articleDetail.value)

  if (articleDetail.value.article.articleId !== 0) {
    // TODO 获取关联文章
    console.log('获取关联文章')
    await getArticleById({
      userId: store.userId,
      articleId: articleDetail.value.article.articleId
    }).then(res => {
      console.log('res => ',res)
      if (res.data !== null) {
        relatedArticle.value = res.data
      } else {
        relatedArticle.value = null
      }
      console.log('relatedArticle => ',relatedArticle.value)
    })
  }
})

const goodJobOnClick = () => {
  // TODO 点赞
  if (articleDetail.value.like) {
    showToast('已点赞')
  } else {
    like({
      userId: store.userId,
      articleId: articleId
    }).then(res => {
      if (res.code === 200) {
        showToast(res.message)
        articleDetail.value.like = true
      } else {
        showToast(res.message)
      }
    })
  }

}

const collectOnClick = () => {
  // TODO 收藏
  if (articleDetail.value.collect) {
    cancelCollect({
      userId: store.userId,
      articleId: articleId
    }).then(res => {
      showToast(res.message)
      articleDetail.value.collect = false
    })
  } else {
    collect({
      userId: store.userId,
      articleId: articleId
    }).then(res => {
      if (res.code === 200) {
        showToast(res.message)
        articleDetail.value.collect = true
      } else {
        showToast(res.message)
      }
    })
  }
}

const updateArticleOnClick = () => {
  let params = {
    type: 1,//1表示修改文章
    articleId: articleDetail.value.article.id
  }

  localStorage.setItem('articleId', JSON.stringify(params));
  router.push('/write')
}

const writeArticleOnClick = () => {
  let params = {
    type: 2,//2表示有关联文章文章
    articleId: articleDetail.value.article.id
  }

  localStorage.setItem('articleId', JSON.stringify(params))
  router.push('/write')
}
</script>

<template>
  <van-nav-bar fixed left-arrow @click-left="goBackToThePreviousPage">
    <template #right>
      <div class="nav-right">
        <van-icon name="search" size="18" @click="router.push('/search')"/>
        <van-icon name="home-o" size="18" @click="router.push('/')"/>
      </div>
    </template>
  </van-nav-bar>

  <div class="app-container">
    <div class="article-info-box">
      <div class="title">
        <h3>{{ articleDetail.article.title }}</h3>
      </div>
      <div class="tags">
        <span>知识库：</span>
        <van-tag v-for="knowledgeBase in articleDetail.knowledgeBases" plain type="primary">{{
            knowledgeBase.name
          }}
        </van-tag>
      </div>
      <div class="article-ta">
        <div class="author">{{ articleDetail.user.username }}</div>
        <div class="time">{{ articleDetail.article.updateTime }}</div>
      </div>
    </div>

    <DisplayHTML :article-content="articleDetail.article.content"></DisplayHTML>

    <!-- 关联文章展示 -->
    <van-cell :style="{marginTop: '1rem'}" title="关联文章">
      <template #label>
        <div v-if="relatedArticle === null">无关联文章</div>
        <ArticleItem v-else :article="relatedArticle.article" :user="relatedArticle.user" :knowledge-bases="relatedArticle.knowledgeBases"></ArticleItem>
      </template>
    </van-cell>
  </div>

  <van-action-bar>
    <van-action-bar-icon :color="`${articleDetail.like ? '#ffcc00' : '#cccccc'}`" icon="good-job" text="点赞"
                         @click="goodJobOnClick"/>
    <van-action-bar-icon :color="`${articleDetail.collect ? '#ffcc00' : '#cccccc'}`" icon="star" text="收藏"
                         @click="collectOnClick"/>
    <van-action-bar-icon icon="chat" text="评论" @click="showRemarkBox = true"/>
    <van-action-bar-button text="引用" type="success" @click="writeArticleOnClick"/>
    <van-action-bar-button v-if="store.userId === articleDetail.article.userId" text="修改" type="warning"
                           @click="updateArticleOnClick"/>
  </van-action-bar>


  <!-- 评论 -->
  <van-popup v-model:show="showRemarkBox" :style="{ height: '66%'}" close-icon="cross" closeable
             position="bottom">
    <Remark :article-id="articleId"></Remark>
  </van-popup>
</template>

<style lang="scss" scoped>
.nav-right {
  display: grid;
  grid-gap: .5rem;
  grid-template-columns: 1fr 1fr;
}

.app-container {
  margin-top: 3rem;
  padding: .5rem;
  box-sizing: border-box;
  overflow: auto;

  .article-info-box {
    box-sizing: border-box;
    width: 100%;
    height: fit-content;
    padding: .5rem;
    background-color: #fff;

    .article-ta {
      display: flex;
      justify-content: space-between;
      margin-top: .5rem;

      .time, .author {
        color: #999;
      }
    }

    .tags {
      display: flex;
      gap: .5rem;
      align-items: center;
    }
  }

  .article-content {
    box-sizing: border-box;
    margin-top: 1rem;
    padding: 0 .5rem;
    background-color: #fff;
  }
}

.article-bottom {
  display: flex;
  justify-content: space-between;
  margin-top: 1rem;

  .van-button {
    width: 49%;
  }
}
</style>